<?php

namespace app\api\logic;

use think\facade\Db;
use app\common\RedisClient;
use think\facade\Log;
use app\admin\model\Algorithm;
use app\api\service\ProductMerge;

class CacheLogic
{
    /**
     * 缓存键定义
     */
    private const CACHE_KEYS = [
        'brand' => [
            'info_prefix' => 'publicCategories.brands:',
            'zset_key' => 'publicCategories.brands:sorted'
        ],
        'coin' => [
            'info_prefix' => 'publicCategories.coins:',
            'zset_key' => 'publicCategories.coins:sorted'
        ],
        'algorithm' => [
            'info_prefix' => 'publicCategories.algorithms:',
            'zset_key' => 'publicCategories.algorithms:sorted'
        ],
        'accessory' => [
            'info_prefix' => 'publicCategories.accessory:',
            'zset_key' => 'publicCategories.accessory:sorted'
        ],
        'solution' => [
            'info_prefix' => 'publicCategories.solution:',
            'zset_key' => 'publicCategories.solution:sorted'
        ],
        'product' => [
            'info_prefix' => 'products',  // 商品详情
            // 'sorted' => 'sorted',    // 商品排序集合
            // 'hot_key' => 'products:hot',
            // 'top_key' => 'products:top',
        ]
    ];
    private const CACHE_EXPIRE = 2 * 24 * 3600; // 2天 = 2 * 24 * 3600 秒
    private const PRODUCT_CACHE_EXPIRE = 2 * 3600; // 2H = 2 * 3600 秒


    protected $redis;
    protected $lang;

    public function __construct()
    {
        $this->redis = (new RedisClient())->getClient();
    }

    /**
     * @describe 清除所有缓存
     * @author: Bobo
     * @date: 2025-04-24 13:11:22 
     * @param [type] @required
     * @return Renderable
     */
    public function clearCache($type)
    {
        $clearCache = function ($infoKeys) {
            // 清理 info_prefix 相关的键
            if (isset($infoKeys['info_prefix'])) {
                $pattern = $infoKeys['info_prefix'] . '*';
                $keys = $this->redis->keys($pattern);
                if (!empty($keys)) {
                    $this->redis->del($keys);
                }
            }
            // 清理 zset_key
            if (isset($infoKeys['zset_key'])) {
                $this->redis->del($infoKeys['zset_key']);
            }
        };

        try {
            switch ($type) {
                case 1:
                    $infoKeys = self::CACHE_KEYS['brand'];
                    break;
                case 2:
                    $infoKeys = self::CACHE_KEYS['coin'];
                    break;
                case 3:
                    $infoKeys = self::CACHE_KEYS['algorithm'];
                    break;
                case 4:
                case 5:
                    $accessoryInfoKeys = self::CACHE_KEYS['accessory'];
                    $solutionIinfoKeys = self::CACHE_KEYS['solution'];
                    $clearCache($accessoryInfoKeys);
                    $clearCache($solutionIinfoKeys);
                    return;
                    break;
                case 6:
                    $brandInfoKeys = self::CACHE_KEYS['brand'];
                    $coinInfoKeys = self::CACHE_KEYS['coin'];
                    $algorithmInfoKeys = self::CACHE_KEYS['algorithm'];
                    $accessoryInfoKeys = self::CACHE_KEYS['accessory'];
                    $solutionInfoKeys = self::CACHE_KEYS['solution'];
                    $productInfoKeys = self::CACHE_KEYS['product'];
                    $clearCache($brandInfoKeys);
                    $clearCache($coinInfoKeys);
                    $clearCache($algorithmInfoKeys);
                    $clearCache($accessoryInfoKeys);
                    $clearCache($solutionInfoKeys);
                    $clearCache($productInfoKeys);
                    return;
                    break;
                default:
                    return true;
            }

            return $clearCache($infoKeys);
        } catch (\Exception $e) {
            // 记录日志
            Log::error('清除缓存失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 通用获取数据方法
     */
    private function getAllItems($zsetKey, $infoPrefix, $cacheDataCallback, $refresh = false, $sort = 'desc')
    {
        if ($refresh || !$this->redis->exists($zsetKey)) {
            return $cacheDataCallback($this->redis);
        }
        try {
            if ($sort == 'desc') {
                $ids = $this->redis->zRevRange($zsetKey, 0, -1);
            } else {
                $ids = $this->redis->zRange($zsetKey, 0, -1);
            }
            if (empty($ids)) {
                return $cacheDataCallback($this->redis);
            }

            $result = [];
            foreach ($ids as $id) {
                $key = $infoPrefix . $id;
                if ($this->redis->exists($key)) {
                    $data = $this->redis->hGetAll($key);
                    $data['id'] = $id;
                    $result[] = $data;
                } else {
                    return $cacheDataCallback($this->redis);
                }
            }
            return $result;
        } catch (\Exception $e) {
            Log::error("Redis获取数据异常: {$zsetKey} " . $e->getMessage());
            return $cacheDataCallback($this->redis);
        }
    }

    /**
     * 清理旧缓存数据
     * @param array|string $cacheKeys 缓存键配置
     */
    private function clearOldCache($cacheKeys)
    {
        try {
            if (is_array($cacheKeys)) {
                // 如果是数组格式的缓存键配置
                foreach ($cacheKeys as $key => $value) {
                    if (isset($value['info_prefix'])) {
                        $pattern = $value['info_prefix'] . '*';
                        $keys = $this->redis->keys($pattern);
                        if (!empty($keys)) {
                            $this->redis->del($keys);
                        }
                    }
                }
            } else {
                // 如果是字符串格式的缓存键
                if ($this->redis->exists($cacheKeys)) {
                    $this->redis->del($cacheKeys);
                }
            }
        } catch (\Exception $e) {
            Log::error('清理缓存失败', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
        }
    }

    /**
     * 获取所有品牌
     */
    public function getAllBrands($lang, $refresh = false, $sort = 'asc')
    {
        $this->lang = $lang;
        $data = $this->getAllItems(
            self::CACHE_KEYS['brand']['zset_key'],
            self::CACHE_KEYS['brand']['info_prefix'],
            [$this, 'cacheBrandsData'],
            $refresh,
            $sort
        );
        return translate($data, $this->lang, ['name', 'description'], ['translate_name', 'description']);
    }

    /**
     * 缓存品牌数据
     */
    private function cacheBrandsData()
    {
        try {
            // 构建子查询
            $subQuery = Db::table('db_product')->alias('p')
                ->join('db_product_relation r', 'r.pid = p.id')
                ->join('db_product_merge m', 'm.id = r.pm_id')
                ->where([
                    ['p.is_del', '=', 0],
                    ['p.type', '=', 1],
                    ['r.is_del', '=', 0],
                    ['m.is_del', '=', 0],
                    ['m.status', '=', '1']
                ])
                ->field('p.brand, COUNT(DISTINCT r.pm_id) as num')
                ->group('p.brand')
                ->buildSql();

            // 主查询
            $brands = Db::table('db_product_brand')->alias('b')
                ->join([$subQuery => 'tmp'], 'tmp.brand = b.id')
                ->where('b.is_del', 0)
                ->field([
                    'b.id',
                    'b.name',
                    'b.description',
                    'b.firmware_url',
                    'b.image',
                    'b.sort_order as sort',
                    'IFNULL(tmp.num, 0) as num'
                ])
                ->order('sort asc')
                ->select()
                ->toArray();
 
            $this->clearOldCache(
                self::CACHE_KEYS['brand']['zset_key'],
                self::CACHE_KEYS['brand']['info_prefix']
            );


            $this->redis->pipeline(function ($pipe) use ($brands) {
                foreach ($brands as $brand) {
                    if (empty($brand['id'])) continue;

                    $brandKey = self::CACHE_KEYS['brand']['info_prefix'] . $brand['id'];
                    $pipe->hMSet($brandKey, [
                        'name' => $brand['name'] ?? '',
                        'description' => $brand['description'] ?? '',
                        'image' => $brand['image'] ?? '',
                        'sort' => $brand['sort'] ?? 0,
                        'num' => $brand['num'] ?? 0
                    ]);
                    $pipe->expire($brandKey, self::CACHE_EXPIRE); // 添加过期时间
                    $pipe->zAdd(self::CACHE_KEYS['brand']['zset_key'], intval($brand['sort']), $brand['id']);
                }
                $pipe->expire(self::CACHE_KEYS['brand']['zset_key'], self::CACHE_EXPIRE);
            });

            return $brands;
        } catch (\Exception $e) {
            Log::error('Redis缓存品牌数据异常: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * 获取所有币种
     */
    public function getAllCoins($lang, $refresh = false)
    {
        $data =  $this->getAllItems(
            self::CACHE_KEYS['coin']['zset_key'],
            self::CACHE_KEYS['coin']['info_prefix'],
            [$this, 'cacheCoinsData'],
            $refresh,
            'asc'
        );

        return  translate($data, $lang, ['name', 'description']);
    }

    /**
     * 缓存币种数据
     */
    private function cacheCoinsData()
    {
        try {
            $algorithmsList = (array) $this->getAllAlgorithms($this->lang, $this->redis);
            $algorithmsList = array_column($algorithmsList, null, 'id');
            $algorithmsIds = array_column($algorithmsList, 'id');

            $coinsList = Db::name('product_currency')
                ->field('id,name_short as name, image, algorithm, name_short as abbr,0 as num,sort')
                ->where('is_del', 0)
                ->where('if_show', 1)
                ->whereIn('algorithm', $algorithmsIds)
                ->order('sort asc')
                ->select()
                ->toArray();

            foreach ($coinsList as &$coin) {
                $coin['num'] = $algorithmsList[$coin['algorithm']]['num'] ?? 0;
            }

            $this->clearOldCache(
                self::CACHE_KEYS['coin']['zset_key'],
                self::CACHE_KEYS['coin']['info_prefix']
            );

            $this->redis->pipeline(function ($pipe) use ($coinsList) {
                foreach ($coinsList as $coin) {
                    $coinKey = self::CACHE_KEYS['coin']['info_prefix'] . $coin['id'];
                    $pipe->hMSet($coinKey, [
                        'name' => $coin['name'] ?? '',
                        'abbr' => $coin['abbr'] ?? '',
                        'algorithm' => $coin['algorithm'] ?? '',
                        'image' => $coin['image'] ?? '',
                        'num' => $coin['num'] ?? 0,
                        'sort' => $coin['sort'] ?? 0
                    ]);
                    $pipe->expire($coinKey, self::CACHE_EXPIRE);
                    $pipe->zAdd(self::CACHE_KEYS['coin']['zset_key'], intval($coin['sort']), $coin['id']);
                }
                $pipe->expire(self::CACHE_KEYS['coin']['zset_key'], self::CACHE_EXPIRE);
            });

            return $coinsList;
        } catch (\Exception $e) {
            Log::error('Redis缓存币种数据异常: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * 获取所有算法
     */
    public function getAllAlgorithms($lang, $refresh = false)
    {
        $this->lang = $lang;
        $data = $this->getAllItems(
            self::CACHE_KEYS['algorithm']['zset_key'],
            self::CACHE_KEYS['algorithm']['info_prefix'],
            [$this, 'cacheAlgorithmsData'],
            $refresh
        );
        return translate($data, $lang, ['name']);
    }

    /**
     * 缓存算法数据
     */
    private function cacheAlgorithmsData($redis)
    {
        try {

            $relatedData = Db::table('db_product')->alias('p')
                ->join('db_product_relation r', 'r.pid = p.id')
                ->join('db_product_merge m', 'm.id = r.pm_id')
                ->where([
                    ['p.is_del', '=', 0],
                    ['r.is_del', '=', 0],
                    ['m.is_del', '=', 0],
                    ['m.status', '=', '1'] // 包含m.status条件
                ])
                ->whereNotNull('p.algorithm')
                ->field([
                    'r.pm_id',
                    'r.pid',
                    'p.algorithm'
                ])
                ->select()
                ->toArray();

            $algorithmModel = new Algorithm();
            $algorithmList = (array)$algorithmModel->getAttributes('algorithm'); // 获取算法名称列表
            $algorithmPmIds = []; // 存储每个算法 ID 对应的去重 pm_id 集合

            foreach ($relatedData as $item) {
                $pmId = $item['pm_id'];
                $algorithms = explode(',', $item['algorithm']);
                foreach ($algorithms as $algId) {
                    $algId = intval($algId); // 确保算法ID是整数
                    if (isset($algorithmList[$algId])) {
                        // 使用算法ID作为键，存储pm_id，确保去重
                        $algorithmPmIds[$algId][$pmId] = $pmId;
                    }
                }
            }

            $algorithmCounts = [];
            foreach ($algorithmPmIds as $algId => $pmIds) {
                $algorithmCounts[] = [
                    'id' => $algId,
                    'name' => $algorithmList[$algId],
                    'num' => count($pmIds) // 统计去重后的pm_id数量
                ];
            }

            uasort($algorithmCounts, function ($a, $b) {
                return $b['num'] - $a['num'];
            });

            $result = array_values($algorithmCounts); // 重新索引数组

            $this->clearOldCache(
                self::CACHE_KEYS['algorithm']['zset_key'],
                self::CACHE_KEYS['algorithm']['info_prefix']
            );

            $this->redis->pipeline(function ($pipe) use ($result) {
                foreach ($result as $algorithm) {
                    $algorithmKey = self::CACHE_KEYS['algorithm']['info_prefix'] . $algorithm['id'];
                    $pipe->hMSet($algorithmKey, [
                        'name' => $algorithm['name'] ?? '',
                        'num' => intval($algorithm['num'])
                    ]);
                    $pipe->expire($algorithmKey, self::CACHE_EXPIRE);
                    $pipe->zAdd(self::CACHE_KEYS['algorithm']['zset_key'], intval($algorithm['num']), $algorithm['id']);
                }
                $pipe->expire(self::CACHE_KEYS['algorithm']['zset_key'], self::CACHE_EXPIRE);
            });

            return $result;
        } catch (\Exception $e) {
            Log::error('Redis缓存算法数据异常: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-15 17:21:15 
     * @param [type] @required
     * @return Renderable
     */
    public function getAllAccessory($solutionType, $lang, $refresh = false)
    {
        // 获取所有数据
        $allData = $this->getAllItems(
            self::CACHE_KEYS['accessory']['zset_key'],
            self::CACHE_KEYS['accessory']['info_prefix'],
            [$this, 'cacheAccessoryData'],
            $refresh
        );

        // 过滤 solution_type
        $data =  array_filter($allData, function ($item) use ($solutionType) {
            return isset($item['solution_type']) && $item['solution_type'] == $solutionType;
        });
        return translate($data, $lang, ['name', 'description'], ['translate_name', 'description']);
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-15 17:23:28 
     * @param [type] @required
     * @return Renderable
     */
    public function cacheAccessoryData($redis)
    {
        try {
            // 构建子查询
            $subQuery = Db::table('db_product')->alias('p')
                ->join('db_product_relation r', 'r.pid = p.id')
                ->join('db_product_merge m', 'm.id = r.pm_id')
                ->whereNotNull('p.category')
                ->where([
                    ['p.is_del', '=', 0],
                    ['p.type', '=', 2],
                    ['r.is_del', '=', 0],
                    ['m.is_del', '=', 0],
                    ['m.status', '=', '1']
                ])
                ->field('p.category, COUNT(DISTINCT r.pm_id) as num')
                ->group('p.category')
                ->buildSql();

            // 主查询
            $categorys = Db::table('db_product_category')->alias('b')
                ->join([$subQuery => 'tmp'], 'tmp.category = b.id')
                ->where([
                    'b.is_del' => 0,
                    'b.solution_type' => 0
                ])
                ->field([
                    'b.id',
                    'b.name',
                    'b.description',
                    'b.image',
                    'b.parent_id',
                    'b.solution_type',
                    'IFNULL(tmp.num, 0) as num'
                ])
                ->order('num desc')
                ->select()
                ->toArray();

            foreach ($categorys as &$category) {
                if ($category['parent_id'] == '') {
                    $sum = array_reduce($categorys, function ($carry, $item) use ($category) {
                        return $carry + ($item['parent_id'] == $category['id'] ? $item['num'] : 0);
                    }, 0);
                    $category['num'] += $sum;
                }
            }
            uasort($categorys, function ($a, $b) {
                return $b['num'] - $a['num'];
            });

            $this->clearOldCache(
                self::CACHE_KEYS['accessory']['zset_key'],
                self::CACHE_KEYS['accessory']['info_prefix']
            );



            $this->redis->pipeline(function ($pipe) use ($categorys) {
                foreach ($categorys as $category) {
                    if (empty($category['id'])) continue;

                    $categoryKey = self::CACHE_KEYS['accessory']['info_prefix'] . $category['id'];
                    $pipe->hMSet($categoryKey, [
                        'name' => $category['name'] ?? '',
                        'description' => $category['description'] ?? '',
                        'image' => $category['image'] ?? '',
                        'solution_type' => $category['image'] ?? '',
                        'num' => $category['num'] ?? 0
                    ]);
                    $pipe->expire($categoryKey, self::CACHE_EXPIRE);
                    $pipe->zAdd(self::CACHE_KEYS['accessory']['zset_key'], intval($category['num']), $category['id']);
                }
                $pipe->expire(self::CACHE_KEYS['accessory']['zset_key'], self::CACHE_EXPIRE);
            });
            return $categorys;
        } catch (\Exception $e) {
            Log::error('Redis缓存品牌数据异常: ' . $e->getMessage());
            return [];
        }
    }


    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-24 13:34:26 
     * @param [type] @required
     * @return Renderable
     */
    public function getAllSolution($lang, $refresh = false)
    {
        // 获取所有数据
        $result =  $this->getAllItems(
            self::CACHE_KEYS['solution']['zset_key'],
            self::CACHE_KEYS['solution']['info_prefix'],
            [$this, 'cacheSolutionData'],
            $refresh
        );
        $result = translate($result, $lang, ['name', 'description'], ['translate_name', 'description']);
        $tree = [];
        $map = [];

        // 首先将所有分类放入map中
        foreach ($result as $category) {
            $map[$category['id']] = $category;
        }

        // 构建树形结构
        foreach ($result as $category) {
            if (empty($category['parent_id'])) {
                // 一级分类直接加入树
                $tree[] = &$map[$category['id']];
            } else {
                // 子分类加入父分类的children数组
                if (isset($map[$category['parent_id']])) {
                    if (!isset($map[$category['parent_id']]['children'])) {
                        $map[$category['parent_id']]['children'] = [];
                    }
                    $map[$category['parent_id']]['children'][] = &$map[$category['id']];
                }
            }
        }

        // 对每个一级分类的子分类按num倒序排序
        foreach ($tree as &$item) {
            if (isset($item['children'])) {
                usort($item['children'], function ($a, $b) {
                    return $b['num'] - $a['num'];
                });
            }
        }

        return $tree;
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-24 13:35:59 
     * @param [type] @required
     * @return Renderable
     */
    public function cacheSolutionData($redis)
    {
        try {
            // 构建子查询
            $subQuery = Db::table('db_product')->alias('p')
                ->join('db_product_relation r', 'r.pid = p.id')
                ->join('db_product_merge m', 'm.id = r.pm_id')
                ->whereNotNull('p.category')
                ->where([
                    ['p.is_del', '=', 0],
                    ['p.type', '=', 2],
                    ['r.is_del', '=', 0],
                    ['m.is_del', '=', 0],
                    ['m.status', '=', '1']
                ])
                ->field('p.category, COUNT(DISTINCT r.pm_id) as num')
                ->group('p.category')
                ->buildSql();

            // 主查询
            $categorys = Db::table('db_product_category')->alias('b')
                ->join([$subQuery => 'tmp'], 'tmp.category = b.id', 'left')
                ->where('b.is_del', 0)
                ->where('b.solution_type', 1)
                ->field([
                    'b.id',
                    'b.name',
                    'b.description',
                    'b.image',
                    'b.parent_id',
                    'b.solution_type',
                    'IFNULL(tmp.num, 0) as num'
                ])
                ->order('num desc')
                ->select()
                ->toArray();


            $this->clearOldCache(
                self::CACHE_KEYS['solution']['zset_key'],
                self::CACHE_KEYS['solution']['info_prefix']
            );



            $this->redis->pipeline(function ($pipe) use ($categorys) {
                foreach ($categorys as $category) {
                    if (empty($category['id'])) continue;

                    $categoryKey = self::CACHE_KEYS['solution']['info_prefix'] . $category['id'];
                    $pipe->hMSet($categoryKey, [
                        'name' => $category['name'] ?? '',
                        'description' => $category['description'] ?? '',
                        'image' => $category['image'] ?? '',
                        'solution_type' => $category['image'] ?? '',
                        'num' => $category['num'] ?? 0,
                        'parent_id' => $category['parent_id'] ?? null
                    ]);
                    $pipe->expire($categoryKey, self::CACHE_EXPIRE);
                    $pipe->zAdd(self::CACHE_KEYS['solution']['zset_key'], intval($category['num']), $category['id']);
                }
                $pipe->expire(self::CACHE_KEYS['solution']['zset_key'], self::CACHE_EXPIRE);
            });
            return $categorys;
        } catch (\Exception $e) {
            Log::error('Redis缓存解决方案数据异常: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * 获取商品
     */
    public function getAllProducts($refresh = false, $ids = [])
    {
        $productKey = self::CACHE_KEYS['product']['info_prefix'];

        $processProductData = function ($productData, $ids) {
            $list = [];
            if ($productData) {
                if (!empty($ids)) { // TOP/HOT
                    $productData = array_column($productData, null, 'id');
                    foreach ($ids as $key => $id) {
                        if (isset($productData[$id])) {
                            $list[] = $productData[$id];
                        }
                    }
                } else {  // ALL
                    $list = $productData;
                }
            }
            return $list;
        };

        $getFromCache = function () use ($productKey, $ids) {
            if ($ids) {
                return array_combine($ids, $this->redis->hMGet($productKey, $ids));
            }
            $list = $this->redis->hGetAll($productKey);
            $ids = json_decode($list['sorted'], true);
            return [$list, $ids];
        };

        try {
            if ($refresh || !$this->redis->exists($productKey)) {
                return $processProductData($this->cacheProductsData(), $ids);
            }

            $result = $getFromCache();
            if (is_array($result[0] ?? null)) {
                list($list, $ids) = $result;
            } else {
                $list = $result;
            }

            $result = [];
            foreach ($ids as $id) {
                if (!isset($list[$id])) {
                    return $processProductData($this->cacheProductsData(), $ids);
                }
                $data = json_decode($list[$id], true);
                $result[] = $data;
            }

            return $result;
        } catch (\Exception $e) {
            Log::error("Redis获取数据异常: {$productKey} " . $e->getMessage());
            return $processProductData($this->cacheProductsData(), $ids);
        }
    }

    /**
     * 缓存商品数据
     */
    public function cacheProductsData()
    {
        try {
            $productMerge = new ProductMerge();
            $productMergeList = (array) $productMerge->getProductMergeData();

            uasort($productMergeList, function ($a, $b) {
                return $b['id'] - $a['id'];
            });
            $this->clearOldCache(
                self::CACHE_KEYS['product']
            );
            $productKey =  self::CACHE_KEYS['product']['info_prefix'];
            $this->redis->pipeline(function ($pipe) use ($productKey, $productMergeList) {
                $sorted = [];
                foreach ($productMergeList as $pkey => $product) {
                    $sorted[] = $product['id'];
                    $pipe->hSet($productKey, $product['id'], json_encode($product, JSON_UNESCAPED_UNICODE));
                }
                $pipe->hSet($productKey, 'sorted', json_encode($sorted, JSON_UNESCAPED_UNICODE));
                $pipe->expire($productKey, self::PRODUCT_CACHE_EXPIRE);
            });

            return $productMergeList;
        } catch (\Exception $e) {
            Log::error(
                'Redis缓存商品合并数据异常: ' . $e->getMessage() .
                    ' 在文件 ' . $e->getFile() .
                    ' 第 ' . $e->getLine() . ' 行'
            );
            return [];
        }
    }


    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-21 13:15:44 
     * @param [type] @required
     * @return Renderable
     */
    public function getHotMiners($refresh = false)
    {
        try {
            $hotMinerIDs = DB::name('recommend_product')->where('is_del', 0)->where('position', 2)->order('sort asc')->column('id,pm_id', 'id');
            $hotMinerIDs = array_column($hotMinerIDs, 'pm_id');
            if ($hotMinerIDs) {
                return $this->getAllProducts($refresh, $hotMinerIDs);
            } else {
                return [];
            }
        } catch (\Exception $e) {
            Log::error("Redis获取HOT矿机数据异常: " . $e->getMessage() . ' 在文件 ' . __FILE__ . ' 第 ' . $e->getLine() . ' 行');
            return [];
        }
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-21 13:19:36 
     * @param [type] @required
     * @return Renderable
     */
    public function getTopMiners($refresh = false)
    {
        try {
            $topMinerIDs = DB::name('recommend_product')->where('is_del', 0)->where('position', 1)->order('sort asc')->column('id,pm_id', 'id');
            $topMinerIDs = array_column($topMinerIDs, 'pm_id');
            if ($topMinerIDs) {
                return $this->getAllProducts($refresh, $topMinerIDs);
            } else {
                return [];
            }
        } catch (\Exception $e) {
            Log::error("Redis获取TOP矿机数据异常: " . $e->getMessage() . ' 在文件 ' . __FILE__ . ' 第 ' . $e->getLine() . ' 行');
            return [];
        }
    }
}
